/*
 * Copyright 2011 Michele Mancioppi [michele.mancioppi@gmail.com]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cave.nice.testMessage.resources;

import java.util.Map;

import javax.mail.internet.InternetAddress;
import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.google.appengine.repackaged.com.google.common.collect.Maps;

import cave.nice.testMessage.templates.TemplateException;
import cave.nice.testMessage.templates.TemplateManager;
import cave.nice.testMessage.templates.TemplateManager.TemplateType;

@Path("/configurations")
public class ConfigurationFileResource extends Resource {

	@GET
	@Path("sendmail/.forward")
	@Produces(MediaType.TEXT_PLAIN)
	public String getForwardFile(@Context ServletContext servletContext, @QueryParam("username") String username) throws WebApplicationException {
		if(username == null) {
			throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity("Required parameter 'username' not provided").build());
		}

		Map<String, Object> params = Maps.newHashMap();
		params.put("username", username);

		try {
			return TemplateManager.getInstance(servletContext).applyTemplate(TemplateType.CONFIGURATIONS_FORWARD, params);
		} catch (TemplateException e) {
			throw new WebApplicationException(Response.serverError().entity(e).build());
		}
	}

	@GET
	@Path("procmail/.procmailrc")
	@Produces(MediaType.TEXT_PLAIN)
	public String getProcmailrcFile(@Context ServletContext servletContext, @QueryParam("emailAddress") InternetAddress emailAddress) throws WebApplicationException {
		if(emailAddress == null) {
			throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity("Required parameter 'emailAddress' not provided").build());
		}

		Map<String, Object> params = Maps.newHashMap();
		params.put("emailAddress", emailAddress.getAddress());

		try {
			return TemplateManager.getInstance(servletContext).applyTemplate(TemplateType.CONFIGURATIONS_PROCMAILRC, params);
		} catch (TemplateException e) {
			throw new WebApplicationException(Response.serverError().entity(e).build());
		}
	}

}
